package com.wsoft.hr.pm.service.impl.sys;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wsoft.constant.redis.RedisKeyConstant;
import com.wsoft.core.cmd.SessionInstanceService;
import com.wsoft.core.exception.Asserts;
import com.wsoft.core.service.CommonMemberService;
import com.wsoft.core.service.RedisService;
import com.wsoft.core.vo.MemberVO;
import com.wsoft.hr.pm.entity.sys.HrMemberOrgRelationEntity;
import com.wsoft.hr.pm.entity.sys.HrOrganizationEntity;
import com.wsoft.hr.pm.mapper.HrMemberOrgRelationMapper;
import com.wsoft.hr.pm.query.sys.HrListQuery;
import com.wsoft.hr.pm.query.sys.MemberHrOrgQuery;
import com.wsoft.hr.pm.service.sys.IHrMemberOrgRelationService;
import com.wsoft.hr.pm.service.sys.IHrOrganizationService;
import com.wsoft.hr.pm.vo.sys.HrMemberVO;
import com.wsoft.service.IMemberCommonService;
import com.wsoft.vo.session.LoginHrOrgVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhanggukai
 * @since 2025年02月17日 15:36:40
 */
@Service
public class HrMemberOrgRelationServiceImpl extends ServiceImpl<HrMemberOrgRelationMapper, HrMemberOrgRelationEntity> implements IHrMemberOrgRelationService , SessionInstanceService {

    @Resource
    private IHrOrganizationService hrOrganizationService;

    @Resource
    private CommonMemberService commonMemberService;


    @Resource
    private RedisService redisService;

    @Resource
    private IMemberCommonService memberCommonService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertRelation(MemberHrOrgQuery query) {
        List<HrMemberOrgRelationEntity> data = new ArrayList<>();
        query.getMemberIds().forEach(memberId -> {
            HrMemberOrgRelationEntity entity = new HrMemberOrgRelationEntity();
            entity.setMemberId(memberId);
            entity.setHrOrgId(query.getHrOrgId());
            data.add(entity);
            HrMemberOrgRelationEntity memberOrgRelation = getMemberOrgRelation(memberId);
            if (ObjUtil.isNotEmpty(memberOrgRelation)){
                Asserts.fail("所选已用户中已存在绩效组织关系");
            }
            boolean save = save(entity);
            if (save){
                //清除用户信息缓存
                String loginName = commonMemberService.getMemberInfo(memberId).getLoginName();
                redisService.del(RedisKeyConstant.USER_INFO_CACHE + loginName);
                memberCommonService.loadUserByUsername(loginName);
            }
        });
    }

    @Override
    public boolean deleteRelation(Long memberId) {
        //清空岗位关系
        QueryWrapper<HrMemberOrgRelationEntity> query = new QueryWrapper<>();
        query.lambda().eq(HrMemberOrgRelationEntity::getMemberId, memberId);
        boolean remove = remove(query);
        if (remove){
            //清除用户信息缓存
            redisService.del(RedisKeyConstant.USER_INFO_CACHE + commonMemberService.getMemberInfo(memberId).getLoginName());
        }
        return remove;
    }

    @Override
    public HrMemberOrgRelationEntity getMemberOrgRelation(Long memberId) {
        QueryWrapper<HrMemberOrgRelationEntity> query = new QueryWrapper<>();
        query.lambda().eq(HrMemberOrgRelationEntity::getMemberId,memberId);
        return getOne(query);
    }

    @Override
    public PageInfo<HrMemberVO> pageMember(HrListQuery query) {

        List<HrMemberVO> result = Collections.emptyList();
        if (query.getHrOrgId() == null){
           return PageInfo.of(result);
        }
        List<HrOrganizationEntity> hrList = hrOrganizationService.listAllHrOrgWithCache();
        HrOrganizationEntity orgById = hrOrganizationService.getOrgById(query.getHrOrgId());
        if (hrList.isEmpty()){
            Asserts.fail("组织架构为空");
        }
        List<Long> collect = hrList.stream().filter(e -> e.getAuthCode().startsWith(orgById.getAuthCode()))
                .map(HrOrganizationEntity::getHrOrgId).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(collect)) {
            QueryWrapper<HrMemberOrgRelationEntity> memberOrgQuery = new QueryWrapper<>();
            memberOrgQuery.lambda().in(HrMemberOrgRelationEntity::getHrOrgId, collect);
            List<HrMemberOrgRelationEntity> list = list(memberOrgQuery);
            Map<Long, HrMemberOrgRelationEntity> map = list.stream().collect(Collectors.toMap(HrMemberOrgRelationEntity::getMemberId, Function.identity()));
            if (!list.isEmpty()) {
                List<Long> memberIds = list.stream().map(HrMemberOrgRelationEntity::getMemberId).collect(Collectors.toList());
                PageHelper.startPage(query.getPageNum(), query.getPageSize());
                List<MemberVO> memberList = commonMemberService.getMemberListByName(memberIds, query.getName(),query.getCode(),query.getPhone());
                PageInfo pageInfo = PageInfo.of(memberList);
                List<MemberVO> pageInfoList = pageInfo.getList();
                result = pageInfoList.stream().map(item -> {
                            HrMemberVO vo = Convert.convert(HrMemberVO.class, item);
                            HrMemberOrgRelationEntity relation = map.get(item.getId());
                            if (relation != null) {
                                vo.setHrOrgId(relation.getHrOrgId());
                            } else {
                                // 处理空值情况
                                vo.setHrOrgId(null);
                            }
                            return vo;
                        })
                        .collect(Collectors.toList());
                pageInfo.setList(result);
                return pageInfo;
            }
        }
        return PageInfo.of(result);
    }


    @Override
    public Object loginInstance(Long memberId) {
        HrMemberOrgRelationEntity entity = getMemberOrgRelation(memberId);
        if (entity == null){
            return Convert.convert(LoginHrOrgVO.class, new HrMemberOrgRelationEntity());
        }
        return Convert.convert(LoginHrOrgVO.class, entity);
    }
}
